package com.mijie.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailUtil {  
	  
    String to = "";// 收件人  
    String from = "";// 发件人
    String senderName = null;
    String host = "";// smtp主机  
    String username = "";  
    String password = "";  
    String filename = "";// 附件文件名  
    String subject = "";// 邮件主题  
    String content = "";// 邮件正文  
    Vector<String> file = new Vector<String>();// 附件文件集合  
  
    public MailUtil() {  
    }  
  
    public MailUtil(String to, String from, String smtpServer,  
            String username, String password, String subject, String content) {  
        this.to = to;  
        this.from = from;  
        this.host = smtpServer;  
        this.username = username;  
        this.password = password;  
        this.subject = subject;  
        this.content = content;  
    }  
  
    public String getSenderName() {
		return senderName;
	}

	public void setSenderName(String senderName) {
		this.senderName = senderName;
	}

    public void setHost(String host) {  
        this.host = host;  
    }  
  
    public void setPassWord(String pwd) {  
        this.password = pwd;  
    }  
  
    public void setUserName(String usn) {  
        this.username = usn;  
    }  
  
    public void setTo(String to) {  
        this.to = to;  
    }  
  
    public void setFrom(String from) {  
        this.from = from;  
    }  
  
    public void setSubject(String subject) {  
        this.subject = subject;  
    }  
  
    public void setContent(String content) {  
        this.content = content;  
    }  
  
  
    public void attachfile(String fname) {  
        file.addElement(fname);  
    }  
  
    public boolean sendMail() {  
  
        // 构造mail session  
        Properties props = new Properties() ;  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.auth", "true");  
        Session session = Session.getDefaultInstance(props,  
                new Authenticator() {  
                    public PasswordAuthentication getPasswordAuthentication() {  
                        return new PasswordAuthentication(username, password);  
                    }  
                });  
  
        try {  
            // 构造MimeMessage 并设定基本的值  
            MimeMessage msg = new MimeMessage(session);  
            if(senderName==null)
            	msg.setFrom(new InternetAddress(from));
            else
            	msg.setFrom(new InternetAddress(from,senderName));
              
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to)) ;  
            msg.setSubject(MimeUtility.encodeText(subject,"gbk","B"));  
  
            // 构造Multipart  
            Multipart mp = new MimeMultipart();  
  
            // 向Multipart添加正文  
            MimeBodyPart mbpContent = new MimeBodyPart();  
            mbpContent.setContent(content, "text/html;charset=gbk");  
              
            // 向MimeMessage添加（Multipart代表正文）  
            mp.addBodyPart(mbpContent);  
  
            // 向Multipart添加附件  
            Enumeration<String> efile = file.elements();  
            while (efile.hasMoreElements()) {  
  
                MimeBodyPart mbpFile = new MimeBodyPart();  
                filename = efile.nextElement().toString();  
                FileDataSource fds = new FileDataSource(filename);  
                mbpFile.setDataHandler(new DataHandler(fds));  
                String filename= new String(fds.getName().getBytes(),"ISO-8859-1");  
  
                mbpFile.setFileName(filename);  
                // 向MimeMessage添加（Multipart代表附件）  
                mp.addBodyPart(mbpFile);  
  
            }  
  
            file.removeAllElements();  
            // 向Multipart添加MimeMessage  
            msg.setContent(mp);  
            msg.setSentDate(new Date());  
            msg.saveChanges() ;  
            // 发送邮件  
              
            Transport transport = session.getTransport("smtp");  
            transport.connect(host, username, password);  
            transport.sendMessage(msg, msg.getAllRecipients());  
            transport.close();  
        } catch (Exception mex) {  
            mex.printStackTrace();  
            return false;  
        }  
        return true;  
    }  
  
    public static void serverStatusReport(String subject,String content){
    	InetAddress addr;
    	String ip = null;
		try {
			addr = InetAddress.getLocalHost();
			if(addr!=null){
				ip = addr.getHostAddress();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
    	MailUtil mail = new MailUtil();
		mail.setHost("smtp.51homi.net");  
		mail.setUserName("server@51homi.net");  
		mail.setSenderName("服务器警报");
		mail.setPassWord("IAMmijie168");  
		mail.setTo("15876689000@139.com");  
		mail.setFrom("server@51homi.net");  
		mail.setSubject(subject);  
		mail.setContent(content+(ip!=null?" server ip:"+ip:"")); 
		mail.sendMail();
    }
    
    public static void main(String[] args) throws InterruptedException{
		String[] email = {"314908705@qq.com","chipun_cheng@163.com","iso10086@gmail.com","zhengzb@live.cn","zhengzb@me.com"};
		for(String e : email){
			MailUtil mail = new MailUtil();
			mail.setHost("smtp.51homi.net");  
			mail.setUserName("homing@51homi.net");  
			mail.setSenderName("HO米官方");
			mail.setPassWord("IAMmijie168");  
			mail.setTo(e);  
			mail.setFrom("homing@51homi.net");  
			mail.setSubject("通知：HO米将去掉昵称登录方式，只用HO米号和邮箱地址登录");  
			mail.setContent("各位亲们，为了满足多数用户对昵称个性化的要求，也配合接下来我们HO米软件的重大更新步骤，在2013年8月3日（明天）0点开始，将取消之前的昵称登录方式，只可使用HO米号和邮箱地址登录，您的邮箱地址是:azha1@163.com，您的HO米号是:503691。即从生效时间开始，大家注册HO米的时候，昵称都可以取自己心中任意想要的名字，登录时请使用HO号或邮箱地址登录。如果此改动给大家造成一定的麻烦，我们深表歉意，我们始终都是为了能更好的服务于大家，为大家提供更多精致有趣几乎完美的体验服务，谢谢大家一直以来对我们的支持，谢谢大家！HO米下载地址:http://51homi.com"); 
			mail.sendMail();
		}
    }
      
}  